package com.wang.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wang.admin.api.model.AdUser;
import com.wang.admin.api.model.AdUserDTO;
import com.wang.admin.mapper.AdUserMapper;
import com.wang.common.model.dto.ResponseResult;
import com.wang.common.model.enums.AppHttpCodeEnum;
import com.wang.util.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 后台管理登录逻辑
 *
 * @author WN
 * @date：2024/03/05 16:23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AdUserService {

    private final AdUserMapper adUserMapper;

    /**
     * 登录接口业务处理
     *
     * @param adUserDTO
     * @return
     */
    public ResponseResult login(AdUserDTO adUserDTO){

        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName, adUserDTO.getName());
        AdUser adUser = adUserMapper.selectOne(wrapper);
        // 非空判断
        if (Objects.isNull(adUser)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 密码比对
        String salt = adUser.getSalt();
        String pswd = adUserDTO.getPassword();
        pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
        log.info("账号：{}，密码明文：{}，加密密文：{}",adUserDTO.getName() ,adUserDTO.getPassword() ,pswd);
        if (!pswd.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 封装数据返回
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);
        return ResponseResult.okResult(map);
    }

}
